$(document).ready(function () {
    var appUpdater = new runtime.air.update.ApplicationUpdaterUI();
    appUpdater.configurationFile = new air.File('app:/update-config.xml'); 
    appUpdater.addEventListener(runtime.air.update.events.UpdateEvent.INITIALIZED, function () { appUpdater.checkNow(); });

    // hack until updater fixed via: http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=72&catid=670&threadid=1373568
    air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, function (e) {
         var opened = air.NativeApplication.nativeApplication.openedWindows;
         for (var i = 0; i < opened.length; i ++) {
               opened[i].close();
         }
     });

    // don't keep asking the user if they're sure they want to update
    appUpdater.isCheckForUpdateVisible = false;
    appUpdater.initialize();

    $('#version').html(jquerydocs.version);
    
    // for auto db updating
    // $(document).bind('api-load-complete', function () {
    //     var json = 'loadDocs(' + $.toJSON(jquerydocs) + ');';
    //     
    //     var myFile = air.File.userDirectory.resolvePath('Sites/test.com/htdocs/jquery-api/api-docs.js');
    //     var myFileStream = new air.FileStream();
    //     myFileStream.open(myFile, air.FileMode.WRITE);
    //     myFileStream.writeUTFBytes(json);
    //     
    //     $('#status').html('Write complete.'); 
    //     
    // });

    // window.nativeWindow.alwaysInFront = true;
    
    // var $search = $('#search').focus(function () {
    //     $search.data('focused', true);
    // }).blur(function () {
    //     $search.data('focused', false);
    // });
    
    // $('#header').mousedown(function (event) {
    //     // window.nativeWindow.startMove();
    // }).mouseup(function () {
    //     if ($search.data('focused')) {
    //         $search.focus();
    //     }
    // });
    
    var $item = $('#item');
    
    var $results = $('#functions').click(function (event) {
        var $fn,
            item,
            html = [],
            blank_iframe = 'index-blank.html',
            q, i,
            win;
            
        if (event.target.nodeName == 'LI') {
            $fn = $(event.target);
            if ($fn.is('.highlighted')) {
                $('#search').keyup();
                return;
            } 
            
            $fn.addClass('highlighted');
            q = $fn.text();
            
            $results.find('li').not(event.target).remove();
            item = jquerydocs.data[$fn.attr('id')];
            
            html.push(item.longdesc || '<p>' + item.desc + '</p>'); // longdesc is usally HTML
            html.push('<h2>Returns</h2>');
            html.push('<p>' + item['return'] + '</p>');
            
            if (item.params.length) {
                html.push('<h2>Parameters</h2>');
                html.push('<ul>');
                for (i = 0; i < item.params.length; i++) {
                    html.push('<li><strong>' + item.params[i].name + '</strong> ');
                    if (item.params[i].type) {
                        html.push('(' + item.params[i].type + ')');
                    }
                    html.push(': ' + item.params[i].desc + '</li>');
                }
                html.push('</ul>');
            }

            for (i = 0; i < item.examples.length; i++) {
                html.push('<h2>Example</h2>');
                if (item.examples[i].desc) html.push('<p>' + item.examples[i].desc + '</p>');
                html.push('<h3>jQuery Code</h3>');
                html.push('<pre>' + item.examples[i].htmlCode + '</pre>');
                
                // this is special code that will convert in to a real running example once run through 'runExample(item)'
                if (item.examples[i].html) {
                   html.push('<div style="position: relative;"><iframe id="' + item.examples[i].exampleId + '" src="index-blank.html" sandboxRoot="http://localhost/" documentRoot="app:/" class="example" src="' + blank_iframe + '"></iframe></div>');
                }
            }

            $item.html(html.join('') + '<div class="clear"></div>').slideDown();
            
            for (i = 0; i < item.examples.length; i++) {
                win = document.getElementById(item.examples[i].exampleId);
                $(win).bind('load', { example: item.examples[i] }, function (event) {
                    var example = event.data.example;
                    this.contentWindow.childSandboxBridge.write(
                        example.runCode
                        .replace("</head>", '<base href="http://docs.jquery.com" /><style>html,body{border:0; margin:0; padding:0;}</style></head>')
                    );
                });
            }
        }
    });
    
    $('#search').keyup(function () {
        var q = $(this).val().toLowerCase().replace( /^\s+|\s+$/g,"");
        $('#count').html('');

        $item.empty().hide();
        
        if (q == '') {
            $results.empty();
            $('#intro').show();
            return;
        } else {
            $('#intro').hide();
        }

        var results = jquerydocs.find(q);
        var args, html = [];
        var j = i = 0;
        for (i = 0; i < results.length; i++) {
            args = [];
            if (results[i].params.length) {
                for (j = 0; j < results[i].params.length; j++) {
                    args.push(results[i].params[j].name);
                }
            }
            html.push('<li id="' + results[i].searchname + results[i].id + '" class="direct">' + results[i].name + '(' + args.join(', ') + ')</li>');
        }
        
        $results.empty().html(html.join(''));
    }).focus();
});
